package com.acdc.mqtt.service.impl;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.acdc.mqtt.entity.ControllerData;
import com.acdc.mqtt.entity.MqttMsg;
import com.acdc.mqtt.entity.MqttMsgType;
import com.acdc.mqtt.entity.UpdateFile;
import com.acdc.mqtt.service.IotModuleSender;
import com.acdc.mqtt.entity.ControlType;
import com.acdc.mqtt.service.MqttProducerService;
import com.acdc.mqtt.config.MqttConfig;
import com.acdc.service.IIotModuleLogService;
import com.acdc.domain.IotModuleLog;
import com.acdc.domain.IotModule;
import com.acdc.service.IIotModuleService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class IotModuleSenderImpl implements IotModuleSender {

    @Autowired
    private MqttProducerService mqttProducerService;

    @Autowired
    private MqttConfig mqttConfig;

    @Autowired
    private IIotModuleLogService iotModuleLogService;

    @Autowired
    private IIotModuleService iotModuleService;

    private static final String SET_TOPIC = "/SET";

    /**
     * 保存IoT模块操作日志
     * @param imei 设备IMEI
     * @param opType 操作类型
     * @param mqttMsg MQTT消息对象
     */
    private void saveIotModuleLog(String imei, String opType, MqttMsg<?> mqttMsg) {
        try {
            IotModule iotModule = iotModuleService.selectIotModuleByImei(imei);
            IotModuleLog iotModuleLog = new IotModuleLog();
            iotModuleLog.setIotModuleId(iotModule.getId());
            iotModuleLog.setOpType(opType);
            
            // 将mqttMsg转换为JSON字符串
            try {
                iotModuleLog.setOpData(new ObjectMapper().writeValueAsString(mqttMsg));
            } catch (JsonProcessingException e) {
                log.error("转换mqttMsg为JSON失败: {}", e.getMessage());
                // 如果JSON转换失败，使用toString()作为备选方案
                iotModuleLog.setOpData(mqttMsg.toString());
            }
            
            iotModuleLog.setOpTime(LocalDateTime.now());
            iotModuleLogService.insertIotModuleLog(iotModuleLog);
        } catch (Exception e) {
            log.error("保存IoT模块日志失败: {}", e.getMessage());
        }
    }

    @Override
    public void setTime(String imei) {
        MqttMsg<ControllerData> mqttMsg = new MqttMsg<>();
        mqttMsg.setStream_id(MqttMsgType.SET);
        ControllerData controllerData = new ControllerData();
        controllerData.setField(ControlType.DATE_TIME);
        controllerData.setField_value(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        mqttMsg.setData(controllerData);
        mqttProducerService.publishMessage(mqttConfig.rootTopic() + imei + SET_TOPIC, mqttMsg);

        saveIotModuleLog(imei, ControlType.DATE_TIME.getType(), mqttMsg);
    }

    @Override
    public void openOTA(String imei) {
        MqttMsg<ControllerData> mqttMsg = new MqttMsg<>();
        mqttMsg.setStream_id(MqttMsgType.SET);
        ControllerData controllerData = new ControllerData();
        controllerData.setField(ControlType.OTA);
        controllerData.setField_value("1");
        mqttMsg.setData(controllerData);
        mqttProducerService.publishMessage(mqttConfig.rootTopic() + imei + SET_TOPIC, mqttMsg);

        saveIotModuleLog(imei, ControlType.OTA.getType(), mqttMsg);
    }

    @Override
    public void setHeartupTime(String imei, int timeout) {
        MqttMsg<ControllerData> mqttMsg = new MqttMsg<>();
        mqttMsg.setStream_id(MqttMsgType.SET);
        ControllerData controllerData = new ControllerData();
        controllerData.setField(ControlType.UT);
        controllerData.setField_value(String.valueOf(timeout));
        mqttMsg.setData(controllerData);
        mqttProducerService.publishMessage(mqttConfig.rootTopic() + imei + SET_TOPIC, mqttMsg);

        saveIotModuleLog(imei, ControlType.UT.getType(), mqttMsg);
    }

    @Override
    public void sentOTA(String imei, int num, int len, String hex, int chk, String flag) {
        MqttMsg<ControllerData> mqttMsg = new MqttMsg<>();
        mqttMsg.setStream_id(MqttMsgType.SET);
        UpdateFile updateFile = new UpdateFile();
        updateFile.setField(ControlType.FILE);
        updateFile.setNum(String.valueOf(num));
        updateFile.setLen(String.valueOf(len));
        updateFile.setDat(hex.replaceAll(" ", ""));
        updateFile.setFlag(flag);
        // chk 改成HEX字符串
        updateFile.setChk(Integer.toHexString(chk));
        mqttMsg.setData(updateFile);
        mqttProducerService.publishMessage(mqttConfig.rootTopic() + imei + SET_TOPIC, mqttMsg);

        saveIotModuleLog(imei, ControlType.OTA.getType(), mqttMsg);
    }

    @Override
    public void setPwrSta(String imei, int pwrSta) {
        MqttMsg<ControllerData> mqttMsg = new MqttMsg<>();
        mqttMsg.setStream_id(MqttMsgType.SET);
        ControllerData controllerData = new ControllerData();
        controllerData.setField(ControlType.KJ);
        controllerData.setField_value(String.valueOf(pwrSta));
        mqttMsg.setData(controllerData);
        mqttProducerService.publishMessage(mqttConfig.rootTopic() + imei + SET_TOPIC, mqttMsg);

        saveIotModuleLog(imei, ControlType.KJ.getType(), mqttMsg);
    }
}
